/**
 * https://www.bilibili.com/video/BV1Mb411e7re?p=38
 * 红外遥控&红外遥控电机调速
 * time: 00:48:00
 */
#include <REGX52.H>
#include "Link/Timer0_Utils.h"
#include "Link/Nixie_Tube_Utils.h"
#include "Link/UART_Utils.h"
#include "Link/Remote_Control_KV.h"
#include "Link/Motor_Utils.h"
#include "Link/IR_HS0038_Utils.h"

static void IR_HS0038_onReceive(unsigned char isRepeat, unsigned char Address, unsigned char Command);
static void Timer0_onTick();

void main_IR_control_Motor() {
    UART_Init(0, 4800);
    UART_sendString("Motor!", 1);

    //初始化红外
    IR_HS0038_Init();
    IR_HS0038_setOnTickListener(&IR_HS0038_onReceive);

    /**
     * 2.直流电机调速(10KHz~20KHz, 频率低了电机会抖动, 高了占用CPU资源.)
     * 100us溢出1次, 1秒溢出10K次
     */
    Timer0_Init(100, 0);
    Timer0_setOnTickListener_Exact(1, &Timer0_onTick);

    while (1);
}

//isRepeat: 是否是重复接收 (遥控器按住不放)
//Address: 地址码 (遥控器的地址, 每种遥控器地址不一样?)
//Command: 命令码 (遥控器按的按键的编号)
static void IR_HS0038_onReceive(unsigned char isRepeat, unsigned char Address, unsigned char Command) {
    //转速
    static unsigned char Speed = 0;
    //不要连发(一直按着)
    if (isRepeat) return;
    
    //根据遥控器命令码设置速度
    if(Command == IR_0) { Speed = 0; }
    else if(Command == IR_1) { Speed = 1; }
    else if(Command == IR_2) { Speed = 2; }
    else if (Command == IR_3) { Speed = 3; }
    switch (Speed) {
        case 0: Motor_SetSpeed(0); break;
        case 1: Motor_SetSpeed(50); break;
        case 2: Motor_SetSpeed(75); break;
        case 3: Motor_SetSpeed(100); break;
        default: break;
    }
    Nixie_Tube_Light_Num(1, 1, Speed, 0, 0);
    UART_sendStringFormat(1, "isRepeat=%bu, Address=%bu, Command=%bu", isRepeat, Address, Command);
}

static void Timer0_onTick() {
    //100μs调用1次
    Motor_CallOnTimer();
}
